from flask import Blueprint, request, jsonify
from app import db
from models.supplychain import Supplier, PurchaseOrder, PurchaseOrderItem
from models.production import Product
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime

bp = Blueprint('supplychain', __name__, url_prefix='/api/supplychain')

@bp.route('/suppliers', methods=['GET'])
@jwt_required()
def get_suppliers():
    """获取供应商列表"""
    try:
        suppliers = Supplier.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取供应商列表成功',
            'data': [supplier.to_dict() for supplier in suppliers]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取供应商列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/suppliers', methods=['POST'])
@jwt_required()
def create_supplier():
    """创建供应商"""
    try:
        data = request.get_json()
        
        # 检查必需字段
        required_fields = ['code', 'name']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查供应商编码是否已存在
        existing_supplier = Supplier.query.filter_by(code=data['code']).first()
        if existing_supplier:
            return jsonify({
                'code': 400,
                'message': '供应商编码已存在',
                'data': None
            }), 400
        
        # 创建新供应商
        supplier = Supplier(
            code=data['code'],
            name=data['name'],
            contact_person=data.get('contact_person'),
            phone=data.get('phone'),
            email=data.get('email'),
            address=data.get('address'),
            bank_name=data.get('bank_name'),
            bank_account=data.get('bank_account'),
            tax_number=data.get('tax_number'),
            status=data.get('status', 'ACTIVE')
        )
        
        db.session.add(supplier)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建供应商成功',
            'data': supplier.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建供应商失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/purchase-orders', methods=['GET'])
@jwt_required()
def get_purchase_orders():
    """获取采购订单列表"""
    try:
        orders = PurchaseOrder.query.filter_by(is_deleted=False).all()
        return jsonify({
            'code': 200,
            'message': '获取采购订单列表成功',
            'data': [order.to_dict() for order in orders]
        }), 200
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': f'获取采购订单列表失败: {str(e)}',
            'data': None
        }), 500

@bp.route('/purchase-orders', methods=['POST'])
@jwt_required()
def create_purchase_order():
    """创建采购订单"""
    try:
        data = request.get_json()
        current_user_id = get_jwt_identity()
        
        # 检查必需字段
        required_fields = ['supplier_id', 'order_date', 'items']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'code': 400,
                    'message': f'缺少必需字段: {field}',
                    'data': None
                }), 400
        
        # 检查供应商是否存在
        supplier = Supplier.query.get(data['supplier_id'])
        if not supplier:
            return jsonify({
                'code': 400,
                'message': '供应商不存在',
                'data': None
            }), 400
        
        # 检查产品是否存在
        for item_data in data['items']:
            product = Product.query.get(item_data['product_id'])
            if not product:
                return jsonify({
                    'code': 400,
                    'message': f'产品不存在: {item_data["product_id"]}',
                    'data': None
                }), 400
        
        # 计算总金额
        total_amount = 0
        for item_data in data['items']:
            amount = item_data['quantity'] * item_data['unit_price']
            total_amount += amount
            item_data['amount'] = amount
        
        # 创建采购订单
        order = PurchaseOrder(
            order_no=f"PO{datetime.now().strftime('%Y%m%d%H%M%S')}",
            supplier_id=data['supplier_id'],
            order_date=datetime.strptime(data['order_date'], '%Y-%m-%d').date(),
            delivery_date=datetime.strptime(data['delivery_date'], '%Y-%m-%d').date() if data.get('delivery_date') else None,
            total_amount=total_amount,
            created_by=current_user_id
        )
        
        db.session.add(order)
        db.session.flush()  # 获取order.id用于明细
        
        # 创建订单明细
        for item_data in data['items']:
            item = PurchaseOrderItem(
                order_id=order.id,
                product_id=item_data['product_id'],
                quantity=item_data['quantity'],
                unit_price=item_data['unit_price'],
                amount=item_data['amount'],
                unit=item_data.get('unit')
            )
            db.session.add(item)
        
        db.session.commit()
        
        # 重新查询以获取完整数据（包括明细）
        order = PurchaseOrder.query.get(order.id)
        
        return jsonify({
            'code': 200,
            'message': '创建采购订单成功',
            'data': order.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'message': f'创建采购订单失败: {str(e)}',
            'data': None
        }), 500